

'''

腾讯漫画

'''
import execjs, json, requests ,re, os
from config import *
from fake_useragent import UserAgent


ua = UserAgent()

class TencentCommic( object ):

    def __init__(self):

        pass

    # 请求详情页面
    def requestHtml(self):

        r = requests.get( url = domain["target_url"],headers=header)

        if r.status_code == 200:

            # 获取加密内容
            res = self.parseHtml( r.text ).replace('\'','')

            # 获取加密签名
            nonce = self.nonceParse(r.text)

            # 数据解码
            pics = self.decodeHtml( res ,nonce)

            #加入下载器
            self.downloader( pics )


        return None


    #解析详情页面
    def parseHtml(self,html):

        content = re.search(r'    var DATA        = (.*),',html).group(1)

        return content


    #数据解码
    def decodeHtml(self,con=None,nonce=None):

        js = open('./jiema.js', mode='r', encoding='utf-8').read()

        cxt = execjs.compile( js )

        items = cxt.call('main',con,nonce)

        result = json.loads( items )

        return result

    #获取nonce签名
    def nonceParse(self,html):

        nonce = re.search('window(\[.*);', html).group(0)


        # 字符串切片
        js = (nonce[20:])

        js = 'function  getNonce() {nonce = ' + js + ';return nonce};'

        cxt = execjs.compile(js)

        nonce = cxt.call('getNonce')

        return nonce

    # 下载漫画
    def downloader(self,pics):

        title = pics['comic']['title']

        chapter = pics['chapter']['cTitle']

        # 在本目录创建文件夹

        save_dir = './{0}/{1}'.format( title,chapter)

        if not os.path.exists( save_dir ):

            os.makedirs( save_dir )

        pictures = pics['picture']

        # 遍历写入
        for pic in pictures:

            loader = lambda : requests.get( url = pic['url'],headers={'User-Agent': ua.random})

            if loader().status_code == 200:

                with open('{0}/{1}.jpg'.format( save_dir,str( pic['pid'])),mode='wb+')  as f:

                    f.write( loader().content)

                    print('写入漫画成功:%s'%pic['url'])

if __name__ == '__main__':


    t = TencentCommic()
    t.requestHtml()
